/**
 * IndexCtrl.java   2017年4月14日 下午4:46:27 by xuebing 
 *
 * Copyright (c) 2010 - 2017 All rights reserved.
 * 
 */
package com.rongmai.web.ctrl;

import com.rongmai.db.exception.BzException;
import com.rongmai.db.model.BaseResult;
import com.rongmai.db.model.User;
import com.rongmai.db.vo.UserVo;
import com.rongmai.web.bo.MessageBo;
import com.rongmai.web.bo.UserBo;
import com.rongmai.web.dto.MessageDTO;
import com.rongmai.web.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginCtrl {

    @Resource
    private MessageBo messageBo;
    @Resource
    private UserBo userBo;

    private static List<String> whiteList = Arrays.asList("17708452030","15573492139","15575515355","15510120762",
            "11111111111","11111111112","11111111113","11111111114","11111111115","11111111116","11111111117","11111111118");

    @RequestMapping(value="/sms", method = RequestMethod.GET)
    public BaseResult<MessageDTO> smsLogin(String mobile, String smsCode, HttpServletRequest request){
        try {
            if (!whiteList.contains(mobile)) {
                log.info("开始校验验证码:{},手机号:{}", smsCode, mobile);
                messageBo.checkSms(mobile, smsCode);
            }
            return BaseResult.succ(userBo.login(mobile, request));
        } catch (BzException e) {
            log.error("业务异常", e);
            return BaseResult.fail(e.getMessage());
        } catch (Exception e) {
            log.error("系统异常", e);
            return BaseResult.FAIL;
        }
    }

    @RequestMapping("changeRole")
    public BaseResult<MessageDTO> changeRole(HttpServletRequest request){
        try {
            User currentUser = UserUtils.getCurrentUser(request);
            if (currentUser == null) {
                throw new BzException("请登录");
            }
            List<UserVo> byMobile = userBo.getByMobile(currentUser.getMobile());
            if (CollectionUtils.isEmpty(byMobile) || byMobile.size() == 1) {
                throw new BzException("当前用户只有一个角色，不可切换");
            }
            return BaseResult.succ(userBo.changeRole(request, currentUser));
        } catch (BzException e) {
            log.error("业务异常", e);
            return BaseResult.fail(e.getMessage());
        } catch (Exception e) {
            log.error("系统异常", e);
            return BaseResult.FAIL;
        }
    }
}
